//------------------------------------------------------------------------------ 
//      Copyright (c) 2004, Be Nanashi-San@757 in "Zeta 2" Thread
// 
//      Permission is hereby granted, free of charge, to any person obtaining a 
//      copy of this software and associated documentation files (the "Software"), 
//      to deal in the Software without restriction, including without limitation 
//      the rights to use, copy, modify, merge, publish, distribute, sublicense, 
//      and/or sell copies of the Software, and to permit persons to whom the 
//      Software is furnished to do so, subject to the following conditions: 
// 
//      The above copyright notice and this permission notice shall be included in 
//      all copies or substantial portions of the Software. 
// 
//      THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
//      IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
//      FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
//      AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
//      LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 
//      FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
//      DEALINGS IN THE SOFTWARE. 
// 
//      File Name:   Bookmark2ch.cpp
//      Author:      Be Nanashi-San@757 in "Zeta 2" Thread  
//                   (http://pc5.2ch.net/test/read.cgi/os/1070354122/757) 
//      Description: Bookmark functions 
//------------------------------------------------------------------------------
/*
©2001-2004 Haiku - http://haiku-os.org/

Permission is hereby granted, free of charge, to any person obtaining a 
copy of this software and associated documentation files (the "Software"), 
to deal in the Software without restriction, including without limitation 
the rights to use, copy, modify, merge, publish, distribute, sublicense, 
and/or sell copies of the Software, and to permit persons to whom the 
Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in 
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR 
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, 
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 
OTHER DEALINGS IN THE SOFTWARE.

*/

#include <Debug.h>
#include <Directory.h>
#include <Entry.h>
#include <File.h>
#include <FindDirectory.h>
#include <List.h>
#include <Menu.h>
#include <MenuItem.h>
#include <Message.h>
#include <Messenger.h>
#include <Node.h>
#include <NodeMonitor.h>
#include <storage/Path.h>
#include <fs_index.h>
#include <malloc.h>
#include <stdio.h>
#include <string.h>
#include <String.h>

#include "Bookmark2ch.h"
#include "messages.h"
#include "setting.h"

//TODO:Bookmark2ch自体をBHandlerにするか？
////////////////////////////////////////////////////////////////////////////////
// AddBookmarkMenuItem
// BookMarkメニューにアイテム追加
//
////////////////////////////////////////////////////////////////////////////////
static void
AddBookmarkMenuItem(entry_ref *ref, BMenu *menu)
{
	BNode node(ref);
	BString url;
	node.ReadAttrString("META:url", &url);
	BMessage *msg = new BMessage(kMSG_BOOKMARK);
	msg->AddString("url", url);
	menu->AddItem(new BMenuItem(ref->name, msg));
}
////////////////////////////////////////////////////////////////////////////////
// DeleteBookMarkMenuItem
//	Menuから指定されたMenuItemをRemoveしdeleteする
//
////////////////////////////////////////////////////////////////////////////////
static void
DeleteBookMarkMenuItem(BMenuItem *item, BMenu *menu)
{
	BMenu *submenu = item->Submenu();
	menu->RemoveItem(item);
	if (submenu)
		delete submenu;	// 繋がった全てのアイテムがdeleteされるのかは疑問(haikuのソースではいいように思うが)
	else
		delete item;
}
////////////////////////////////////////////////////////////////////////////////
// AddBookmarkRef
//  refがBookmarkファイルならMenuItemにして追加し、ディレクトリーならサブメニューを
//  作って再帰的に追加していく
//  2004.12.9：ディレクトリ判定変更など。
////////////////////////////////////////////////////////////////////////////////
static void
AddBookmarkRef(entry_ref *ref, BMenu *menu)
{
	if (!menu) return;
	
	BDirectory  dir;
	if (dir.SetTo(ref) == B_OK) {
		BMenu *submenu = new BMenu(ref->name);
		menu->AddItem(submenu);
		entry_ref subref;
		while (dir.GetNextRef(&subref) == B_OK)	AddBookmarkRef(&subref, submenu);
	}else {
		AddBookmarkMenuItem(ref, menu);
	}
}
////////////////////////////////////////////////////////////////////////////////
// Bookmark2ch
//
//
////////////////////////////////////////////////////////////////////////////////
Bookmark2ch::Bookmark2ch(BMenu *menu, BMessenger report)
	: fMenu(menu)
	, fReport(report)
{
	find_directory(B_USER_SETTINGS_DIRECTORY, &fPath);
	fPath.Append(kBOOKMARK_DIR_NAME);

	this->BuildBookmarkMenu();

	BEntry entry(fPath.Path());
	node_ref nref;
	entry.GetNodeRef(&nref);
	index_info info;
	if (fs_stat_index(nref.device, "META:url", &info) != B_OK)
		fs_create_index(nref.device, "META:url", B_STRING_TYPE, 0);

	watch_node(&nref, B_WATCH_DIRECTORY, fReport);
}
////////////////////////////////////////////////////////////////////////////////
// ~Bookmark2ch
//
//
////////////////////////////////////////////////////////////////////////////////
Bookmark2ch::~Bookmark2ch()
{
	stop_watching(fReport);
}
////////////////////////////////////////////////////////////////////////////////
// BuildBookmarkMenu
//
////////////////////////////////////////////////////////////////////////////////
void
Bookmark2ch::BuildBookmarkMenu()
{
	BDirectory  dir(fPath.Path());
	entry_ref subref;
	while (dir.GetNextRef(&subref) == B_OK) {
		AddBookmarkRef(&subref, fMenu);
	}
}
////////////////////////////////////////////////////////////////////////////////
// BookMarkFileAdded
//
//
////////////////////////////////////////////////////////////////////////////////
void
Bookmark2ch::BookMarkFileAdded(BMessage *msg, const char *fromdir)
{
entry_ref ref;

	msg->FindInt32("device", &ref.device);
	msg->FindInt64(fromdir, &ref.directory);
	ref.set_name(msg->FindString("name"));
	AddBookmarkRef(&ref, this->FindMenu(&ref));
}
////////////////////////////////////////////////////////////////////////////////
// BookMarkFileRemoved
//
//
////////////////////////////////////////////////////////////////////////////////
void
Bookmark2ch::BookMarkFileRemoved(BMessage *msg, const char *fromdir)
{
entry_ref ref;

	msg->FindInt32("device", &ref.device);
	msg->FindInt64(fromdir, &ref.directory);
	ref.set_name(".");
	this->SyncMenu(&ref, this->FindMenu(&ref));
}
////////////////////////////////////////////////////////////////////////////////
// WatchMessage
//	B_NODE_MONITORを処理する
//  戻り値がfalseなら処理しなかった
// 20060715: void
////////////////////////////////////////////////////////////////////////////////
void
Bookmark2ch::WatchMessage(BMessage *msg)
{
	switch (msg->FindInt32("opcode")) {
		case B_ENTRY_CREATED:
			this->BookMarkFileAdded(msg, "directory");
			break;
		case B_ENTRY_MOVED:
			this->BookMarkFileRemoved(msg, "from directory");
			this->BookMarkFileAdded(msg, "to directory");
			break;
		case B_ENTRY_REMOVED:
			this->BookMarkFileRemoved(msg, "directory");
			break;
	}
}
////////////////////////////////////////////////////////////////////////////////
// FindMenu
//	Refに対するMenuを返す
//20060626:strtok
//20061013:コードを戻す。名称変更。
////////////////////////////////////////////////////////////////////////////////
BMenu*
Bookmark2ch::FindMenu(entry_ref *ref)
{
	BMenu *menu = NULL;
	BPath path(ref);
	const char *mpath = fPath.Path();
	char *dpath = strdup(path.Path());
	int32 length= strlen(mpath);
	char *spath = dpath + length;
	*spath++ = '\0';	
	if (strcmp(mpath, dpath) == 0) {
		menu = fMenu;
		while (spath) {
			char *npath = strchr(spath, '/');
			if (npath) *npath++ = '\0';
			BMenuItem *item = menu->FindItem(spath);
			if (item == NULL || item->Submenu() == NULL) break;	// もはや検索不能
			menu  = item->Submenu();
			spath = npath;
		}
	}
	free(dpath);

	return menu;
}
////////////////////////////////////////////////////////////////////////////////
// SyncMenu
//	ディレクトリーとMenuを同期させる(NodeWatchでは何が削除されたかはわからないので)
//  listにMenuのコピーを作りディレクトリーにあるものをlistから削除する。
//  listに残ったものがディレクトリーに無いものなのでMenuから削除する
//
////////////////////////////////////////////////////////////////////////////////
void
Bookmark2ch::SyncMenu(entry_ref *ref, BMenu *menu)
{
	if (!menu) return;
		
	BList list(menu->CountItems());

	int32 countStart = (fMenu == menu) ? 3 : 0; 	// トップのMenuなら先頭から３つは調べちゃだめなので
	for (int32 i = countStart; i < menu->CountItems(); i++)
		list.AddItem(menu->ItemAt(i));

	BDirectory dir(ref);
	entry_ref subref;
	while (dir.GetNextRef(&subref) == B_OK)
		list.RemoveItem(menu->FindItem(subref.name));

	for (int32 i = 0; i < list.CountItems(); i++) {
		DeleteBookMarkMenuItem(static_cast<BMenuItem *>(list.ItemAt(i)), menu);
	}
}
////////////////////////////////////////////////////////////////////////////////
// AddBookmark
//	2chPositiveのBookmarkディレクトリーにBookmarkファイルを追加する
//  同名は後ろに順に番号が付く
//
////////////////////////////////////////////////////////////////////////////////
void
Bookmark2ch::AddBookmark(BMessage *msg)
{
	BString title, url;

	msg->FindString("title", &title);
	msg->FindString("url", &url);
	
	title.ReplaceAll("/", ".");
	BPath path(fPath.Path(), title.String());
	BFile file(path.Path(), B_READ_WRITE | B_CREATE_FILE | B_FAIL_IF_EXISTS);

	int32 sno = 0;		
	char name[B_FILE_NAME_LENGTH + 1];

	status_t state = file.InitCheck();
	while (state == B_FILE_EXISTS) {
		sprintf(name, "%s%ld", path.Path(), ++sno);
		state = file.SetTo(name,  B_READ_WRITE | B_CREATE_FILE | B_FAIL_IF_EXISTS);
	}

	if (state == B_OK) {
		SetBookmarkAttr(&url, &title, &file);
	}else{
		PRINT(("AddBookmark(%s %s) %lx", url.String(), title.String(), state));
	}
}
////////////////////////////////////////////////////////////////////////////////
// OpenBookmarkFolder
//
// 20061018:mainWindowより移動。
////////////////////////////////////////////////////////////////////////////////
void
Bookmark2ch::OpenBookmarkFolder()
{
	entry_ref BookmarkRef;

	get_ref_for_path(fPath.Path(), &BookmarkRef);

	BMessage message(B_REFS_RECEIVED);
	message.AddRef("refs", &BookmarkRef);

	BMessenger messenger("application/x-vnd.Be-TRAK");
	messenger.SendMessage(&message);

}
////////////////////////////////////////////////////////////////////////////////
// SetBookmarkAttr
//  tileでurlのブックマークファイルを作成
// 20061018:Add->Set
////////////////////////////////////////////////////////////////////////////////
void
SetBookmarkAttr(BString *url, BString *title, BFile *file)
{
	const char sign[] = "application/x-vnd.Noname-2chPositive";
	const char mime[] = "application/x-vnd.Noname-2ch+-bookmark";
	file->WriteAttr("BEOS:PREF_APP", B_MIME_TYPE, 0, sign, sizeof(sign));
	file->WriteAttr("BEOS:TYPE", B_MIME_TYPE, 0, mime, sizeof(mime));
	file->WriteAttrString("META:title", title);
	file->WriteAttrString("META:url", url);
}
